package com.btpn.custody.dao.hibernate;

import java.io.Serializable;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.btpn.custody.dao.IGroupRole;
import com.btpn.custody.entity.GroupRole;

@Repository("groupRoleDaoHibernate")
public class GroupRoleDAO implements IGroupRole {

	protected HibernateTemplate template = null;
	
	@Autowired @Required
	public void setSessionFactory(SessionFactory sessionFactory) {
		template = new HibernateTemplate(sessionFactory);
	}

	@Override
	public GroupRole get(Long id) {
		return template.get(GroupRole.class, id);
	}
	
	@Override
	public List<GroupRole> findAll() {
		return template.loadAll(GroupRole.class);
	}
	
	@Override
	public Integer getCount() {
		return Integer.valueOf(findAll().size());
	}
	
	@Override
	public Serializable create(GroupRole groupRole)throws DataAccessException {
		return template.save(groupRole);
	}

	@Override
	public GroupRole update(GroupRole groupRole) {
		template.update(groupRole);
		
		return groupRole;
	}

	@Override
	public void createOrUpdate(GroupRole groupRole) {
		template.saveOrUpdate(groupRole);
	}
	
	@Override
	public void delete(Long id) {
		template.delete(get(id));
	}

	@SuppressWarnings("unchecked")
	@Override
	public GroupRole getByGroupName(String groupName) {
		List<GroupRole> result = template.findByNamedQueryAndNamedParam(GroupRole.NQ__FIND__BY__NAME, "groupName", groupName);
		
		if (result.size()>0) {
			return result.get(0);
		} else {
			return null;
		}
	}
}